<template>
  <div class="con">
    <div class="contbox6_10">
      <div class="titlelist6_10">活动管理 / 开通奖励</div>
      <div class="content">
        <div class="relus">
          活动配置说明：指定的活动押金终端开通后，参与活动的普通代理可获得奖励金额。
          <img @click="relues" src="../../assets/images/sm.png" />
        </div>
        <div class="jibenInfo">基本信息</div>
        <div class="listGroup">
          <div class="lister">
            <div class="listName">活动名称</div>
            <el-input
              :disabled="disNo"
              :maxlength="activeNameLength"
              @focus="selectInstitution"
              v-model="form.activeName"
              style="width: 300px; margin-right: 40px"
            ></el-input>
          </div>
          <!-- <div class="lister">
            <div class="listName">参与对象</div>
            <el-select
              :disabled="disNo || disNos"
              v-model="form.objectType"
              @change="pinChange"
              placeholder="请选择"
              style="width: 278px"
            >
              <el-option
                v-for="item in objectType"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </div>
          <div class="lister" v-if="form.objectType == '1'">
            <div class="listName">选择团队</div>
            <el-cascader
              @remove-tag="delTag"
              ref="cascaderAddr"
              v-model="form.officeUids"
              :disabled="disNo || disNos"
              :options="options"
              :props="{ multiple: true, checkStrictly: true, emitPath: false }"
              clearable
            ></el-cascader>
          </div> -->
          <div class="lister">
            <div class="listName">活动品牌</div>

            <el-select
              :disabled="diss"
              v-model="form.Brand"
              @change="pinChange"
              placeholder="请选择"
            >
              <el-option
                v-for="item in optionsBrand"
                :key="item.uid"
                :label="item.channelName"
                :value="item.uid"
              ></el-option>
            </el-select>
          </div>
          <div class="lister">
            <div class="listName">活动商品</div>
            <el-select
              multiple
              @change="
                xingType(form.BrandTypeNum);
                $forceUpdate();
              "
              v-model="form.BrandTypeNum"
              value-key="productName"
              placeholder="请选择"
              collapse-tags
            >
              <el-option
                label="全选"
                value="全选"
                @click.native="selectAll"
                :disabled="diss"
              ></el-option>
              <el-option
                :disabled="diss"
                v-for="item in optionsBrandTypeNum"
                :key="item.productUid"
                :label="item.productName"
                :value="item.productUid"
              ></el-option>
            </el-select>
          </div>
          <div class="lister">
            <div class="listName">考核时间</div>
            <div class="block">
              <el-date-picker
                :disabled="disNo"
                class="timers"
                value-format="yyyy-MM-dd HH:mm:ss"
                :default-time="['00:00:00', '23:59:59']"
                @input="daterangeChange"
                v-model="form.timers"
                :picker-options="pickerOptions"
                style="width: 200px"
                type="daterange"
                range-separator="至"
                start-placeholder="开始"
                end-placeholder="结束"
              ></el-date-picker>
            </div>
          </div>
          <div class="lister">
            <div class="listName">奖励方式</div>
            <div class="block">
              <el-select
                :disabled="disNo"
                v-model="form.settleType"
                clearable
                placeholder="请选择"
              >
                <el-option label="日结" value="2"></el-option>
                <el-option label="月结" value="3"></el-option>
              </el-select>
            </div>
          </div>
        </div>
        <div class="jibenInfo">规则</div>
        <div class="reward">
          <div class="listers">
            <div class="listNames">开通奖励金额</div>
            <el-input
              :maxlength="9"
              :disabled="disNo"

              @input="value=>{form.openRewardAmt=value.replace(/^\D*(\d*(?:\.\d{0,2})?).*$/g, '$1')}"
              v-model="form.openRewardAmt"
              placeholder=""
              style="margin-right: 10px"
            ></el-input
            >元
          </div>
        </div>
        <div class="jibenInfo">图片配置</div>
        <div style="float: left; width: 96%; margin-left: 20px">
          <p>
            banner图：尺寸345px*140px(图片大小建议不超过1M，请至少上传1张图片，最多可配置3张）
          </p>
          <div style="margin-left: 80px; margin-top: 20px">
            <el-upload
              :class="uploadDisabled"
              :disabled="disNo"
              :action="httpurl + '/api/fileUpload'"
              list-type="picture-card"
              :file-list="form.coverPhotos"
              :on-error="handleFail"
              :limit="3"
              name="file"
              accept=".jpg,.jpeg,.png,.JPG,.JPEG,.PNG"
              :on-preview="handlePictureCardPreview"
              :on-remove="handleRemove"
              :before-upload="beforeAvatarUpload"
              :on-success="success"
            >
              <i class="el-icon-plus"></i>
            </el-upload>
            <el-dialog :visible.sync="dialogVisible">
              <img width="100%" :src="dialogImageUrl" alt="" />
            </el-dialog>
          </div>
        </div>
        <div
          style="float: left; width: 96%; margin-left: 20px; margin-top: 20px"
        >
          <p>
            活动详情图：（图片大小建议不超过1M，请至少上传1张图片，最多可配置3张）
          </p>
          <div style="margin-left: 80px; margin-top: 20px">
            <el-upload
              :class="uploadDisableds"
              :disabled="disNo"
              :action="httpurl + '/api/fileUpload'"
              list-type="picture-card"
              :file-list="form.bgPhotos"
              :limit="3"
              name="file"
              :on-error="handleFail"
              :before-upload="beforeAvatarUpload1"
              accept=".jpg,.jpeg,.png,.JPG,.JPEG,.PNG"
              :on-preview="handlePictureCardPreview1"
              :on-remove="handleRemove1"
              :on-success="success1"
            >
              <i class="el-icon-plus"></i> </el-upload
            ><el-dialog :visible.sync="dialogVisible1">
              <img width="100%" :src="dialogImageUrl1" alt="" />
            </el-dialog>
          </div>
        </div>
        <div class="foot">
          <el-button v-if="!disNo" type="primary" :loading="loading" @click="submit">完成</el-button>
          <el-button v-if="!disNo" @click="result">取消</el-button>
          <el-button v-if="disNo" @click="result">返回</el-button>
        </div>
      </div>
    </div>
    <el-dialog
      title="提示"
      :visible.sync="dialogVisible1"
      width="30%"
      :before-close="handleClose"
    >
      <span>{{ con }}</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="back">取 消</el-button>
        <el-button type="primary" @click="sures">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog title="活动配置说明" width="800px" :visible.sync="dialogVisible3">
      <el-row>
        <el-form label-width="100px">
          <el-form-item label="活动说明：">押金终端开通后，参与活动的普通代理可获得奖励金额，非押金终端不能参与此活动。活动只对选定品牌的商品进行统计。</el-form-item>
          <el-form-item label="考核时间：">考核时间是活动总时间;普通代理参与活动有效期起止时间。</el-form-item>
          <el-form-item label="奖励规则：">在活动时间内，押金终端开通后，参与活动的普通代理则获取奖励金额。</el-form-item>
          <el-form-item label="奖励方式：">日结：当天完成奖励，第二个自然日入账；<br/>月结：当月完成奖励，下月1日入账。</el-form-item>
        </el-form>
      </el-row>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogVisible3 = false"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { Littlehow } from "../../assets/js/util";
import axios from "axios";
import { date } from "../../assets/js/commion";
import https from "../../plugins/https"
import { activeNameLength } from "../../plugins/rules.js"
export default {
  created() {
    this.user = this.$route.query.user;
    // alert(date.isDuringDate('2018/09/17', '2019/09/17'));
    var oemUid = localStorage.getItem("uid");
    https.queryChannelNameList({ oemUid: oemUid })
      .then(res => {
        console.log("品品牌");
        console.log(res.data.data);
        this.optionsBrand = res.data.data;
      })
      .catch(err => {
        console.log(err);
      });

    // this.queryList();
    console.log(this.$route.query.isSshow, this.$route.query.shows);
    this.disNo = this.$route.query.isSshow;
    this.disNos = this.$route.query.isshow;
    this.shows = this.$route.query.shows;
    this.userId = this.$route.query.uid;
    console.log(this.$route.query.uid);
    let uid = this.$route.query.uid;
    if (this.disNo == true) {
      this.uploadDisableds = "disabled";
      this.uploadDisabled = "disabled";
    }
    // console.log(uid);
    // alert(uid);
    // 回显
    if (uid) {
      this.diss=true
      https.queryUpdateActive({ activeUid: uid })
        .then(res => {
          
          this.form = res.data.data;
          // this.form.timers = [];
          this.form.BrandTypeNum = [];
          this.form.Brand = res.data.data.productNoList[0].channelUid;
           if (this.form.coverPhotos.length > 2) {
            this.uploadDisabled = "disabled";
          }
          if (this.form.bgPhotos.length > 2) {
            this.uploadDisableds = "disabled";
          }
          var arr = [];
          arr.push(res.data.data.startDate);
          arr.push(res.data.data.endDate);
          this.$set(this.form, "timers", arr);
          this.pinChange(this.form.Brand);
          // this.form.totalAmt = res.data.data.activeBrandOfficeTop[0].totalAmt;
          // this.num = res.data.data.activeBrandOfficeTop.length + 1;
          this.form.productNoList.channelUid = this.form.Brand;
          https.activeBrand({
              brandChannelId: this.form.Brand
            })
            .then(res1 => {
              this.optionsBrandTypeNum = res1.data.data;
              var temps = [];
              //拿到数组里面的来进行赋值操作
              for (let i = 0; i < res.data.data.productNoList.length; i++) {
                // temps.push()
                temps.push(res.data.data.productNoList[i].productUid);
              }
              this.form.BrandTypeNum = temps;
            })
            .catch(err => {
              console.log(err);
            });
        })
        .catch(err => {
          console.log(err);
        });
    } else {
      this.form.objectType = "0";
    }
  },
  data() {
    return {
      loading:false,
      pickerOptions:{
        disabledDate(time) {
          return time.getTime() < Date.now() //如果没有后面的-8.64e6就是不可以选择今天的
        }
      },
      uploadDisableds:"",
      uploadDisabled:"",
      httpurl: this.GLOBAL.httpurl,
      activeNameLength:activeNameLength,
      dialogVisible3:false,
      diss:false,
      con:"",
      dialogVisible:false,
      objectType: [
        { label: "个人", value: "0" },
        { label: "团队", value: "1" }
      ],
      options: [],
      user: null,
      disNo: true,
      disNos: false,
      shows: false,
      tj: "2020-03-05 - 2020-06-23",
      rewordDate: null, //奖励发放时间
      userId: "",
      startDate: null,
      endDate: null,
      //选择品牌的id
      brandId: null,
      //提交的数据
      form: {
        openRewardAmt:"",
        settleType:"",
        activeUid: "", //活动的id
        activeName: "", //活动的名称
        startDate: "", //活动开始时间
        endDate: "", //活动结束时间
        rewordDate: "", //奖励发放时间
        productNoList: [],
        objectType: "",
        officeUid: localStorage.getItem("uid"),
        oemUid: localStorage.getItem("uid"),
        activeUid:this.$route.uid?this.$route.uid:"",
        totalAmt: "", //活动期间内最低交易总额
        rewardAmt: "", //奖励金额
        activeBrandOfficeTop: [{ level: "1", rewardAmt: "" }],
        timers: [],
        bgPhotos:[],
        coverPhotos:[],
        Brand: "",
        BrandType: "",
        BrandTypeNum: [] //活动商品
      },
      value1: "",
      value2: "",
      //参与活动品牌
      optionsBrand: null,
      Brand: "",
      // 品牌类型
      optionsBrandType: null,
      // BrandType:""
      BrandType: "",
      //   商品型号‘
      optionsBrandTypeNum: null,
      BrandTypeNum: [],
      minimum: "", //入帮交易最低限额
      num: 2,
      rewardGroup: [{ level: "1", rewardAmt: "" }],
      pinpaiId: null,
      xinghaoId: null,
      uid: null
    };
  },
  methods: {
    // 上传成功
    success(res, file, fileList) {
      // 这里是element的上传地址，对应的name,url,自己打印fileList对照
      this.form.coverPhotos.push({ url: res.data.filePath });
      if(this.form.coverPhotos.length>2){
        this.uploadDisabled = "disabled";
      }

    },
    // 删除图片
    handleRemove(res, file, fileList) {
      console.log(res);
      this.uploadDisabled=''
      for (var i = 0; i < this.form.coverPhotos.length; i++) {
        if (this.form.coverPhotos[i].url == res.url) {
          this.form.coverPhotos.splice(i, 1); //删除下标为i的元素
          return this.form.coverPhotos;
        }
      }
    },
    // banner图片上传前的校验
    beforeAvatarUpload(file){
      let newName = file.name.substring(file.name.lastIndexOf("."));
      const isJPG =
        file.type === "image/jpeg" ||
        file.type === "image/png" ||
        file.type === "image/jpg";
      const isLt2M = file.size / 1024 / 1024 < 1000;
      if (!isJPG) {
        // this.$message.error("上传预览图片只能是 jpg、jpeg、png 格式!");
        // return false;
        layer.open({
          content: "上传预览图片只能是 jpg、jpeg、png 格式!",
          skin: "msg",
          time: 2,
        });
        return false;
      } else {
        let that = this;
        const isSize = new Promise((resolve, reject) => {
          // const width = 345;
          // const height = 140;
          const _URL = window.URL || window.webkitURL;
          const img = new Image();
          img.onload = () => {
            let name =
              file.name.substring(0, file.name.lastIndexOf(".")) +
              "_" +
              img.width +
              "_" +
              img.height +
              newName;
            file = new File([file], name);
            const valid = this.$commit.ImageRestrictions(
              img.width,
              img.height,
              1
            );
            valid ? resolve() : reject();
          };
          img.src = _URL.createObjectURL(file);
        }).then(
          () => {
            return file;
          },
          () => {
            // this.$notify({
            //   title: "错误",
            //   message: "图片尺寸限制为345：140，大小不可超过1M",
            //   type: "error",
            // });
            layer.open({
              content: "图片尺寸限制为345：140，大小不可超过1M",
              skin: "msg",
              time: 2,
            });
            return Promise.reject();
          }
        );
        return isSize;
      }
    },
    // 详情图片上传前的校验
    beforeAvatarUpload1(file) {
      let newName = file.name.substring(file.name.lastIndexOf("."));
      const isJPG =
        file.type === "image/jpeg" ||
        file.type === "image/png" ||
        file.type === "image/jpg";
      if (!isJPG) {
        layer.open({
          content: "上传预览图片只能是 jpg、jpeg、png 格式!",
          skin: "msg",
          time: 2,
        });
        return false;
      }
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    // 上传图片
    success1(res, file, fileList) {
      // 这里是element的上传地址，对应的name,url,自己打印fileList对照
      this.form.bgPhotos.push({ url: res.data.filePath });
      if(this.form.bgPhotos.length>2){
        this.uploadDisableds='disabled'
      }
    },
    // 删除
    handleRemove1(res, file, fileList) {
      console.log(res);
      this.uploadDisableds=''
      for (var i = 0; i < this.form.bgPhotos.length; i++) {
        if (this.form.bgPhotos[i].url == res.url) {
          this.form.bgPhotos.splice(i, 1); //删除下标为i的元素
          return this.form.bgPhotos;
        }
      }
    },
    handlePictureCardPreview1(file) {
      this.dialogImageUrl1 = file.url;
      this.dialogVisible1 = true;
    },
    // 点击添加弹框
    relues(){
      this.dialogVisible3=true
    },
    // 全选
    selectAll() {
      this.form.BrandTypeNum = [];
  
      if (this.form.BrandTypeNum.length < this.optionsBrandTypeNum.length) {
        if(this.diss!=true){
        // alert("多选执行")
        var allOption = [];
        for (var i = 0; i < this.optionsBrandTypeNum.length; i++) {
          allOption.push(this.optionsBrandTypeNum[i].productUid);
        }
        this.$set(this.form, "BrandTypeNum", allOption);
        console.log("下面是全选以后后端需要的数据");
        console.log(this.form.BrandTypeNum);
        this.xingType(this.form.BrandTypeNum);
        this.$forceUpdate();
      } }else {
        // alert("取消多选执行")
        var allOption = [];
        this.$set(this.form, "BrandTypeNum", allOption);
        this.xingType(this.form.BrandTypeNum);
        this.$forceUpdate();
      }
    },

    daterangeChange(e) {
      let _this = this;
      console.log(e);
      _this.$nextTick(() => {
        _this.$set(_this.form, "timers", [e[0], e[1]]);
        _this.$forceUpdate();
      });
      this.form.startDate = e[0];
      this.form.endDate = e[1];
    },

    delTag() {
      return false;
    },
    // 查询活动品牌
    queryList() {
      https.activeBrand()
        .then(res => {
          console.log(res);
        })
        .catch(err => {
          console.log(err);
        });
    },
    // 返回  取消
    result() {
      this.$router.push({
        path: "activityManagement"
      });
    },
    isDuringDate(beginDateStr, endDate) {
      var curDate = new Date(),
        beginDate = new Date(beginDateStr),
        endDate = new Date(endDate);
      if (this.form.rewordDate > this.form.endDate) {
        return false;
      } else {
        return true;
      }
    },
    // 确定按钮
    sures(){
      this.form.officeUid=localStorage.getItem('uid')
      axios.post("/api/active/saveOpenRewordActive", this.form).then(res => {
          if (res.data.code == "0000") {
            this.$router.push("activityManagement");
          } else {
            layer.open({
              content: res.data.msg,
              skin: "msg",
              time:  2 //1秒后自动关闭
            });
          }
        });
    },
    back(){
      this.dialogVisible=false
      this.form.BrandTypeNum=[]
      this.form.Brand=""
      // this.xingType()
      this.optionsBrandTypeNum=[]

    },
    submit() {
      this.loading=true
      this.form.activeUid=this.$route.query.uid
      if(this.form.activeName==""){
        return layer.open({
          content: "活动名称不能为空",
          skin: "msg",
          time:  2 //1秒后自动关闭
        });
      }else if(this.form.Brand==""){
        return layer.open({
          content: "活动品牌不能为空",
          skin: "msg",
          time:  2 //1秒后自动关闭
        });
      }else if(this.form.timers.length==0){
        return layer.open({
          content: "考核时间不能为空",
          skin: "msg",
          time:  2 //1秒后自动关闭
        });
      }else if(this.form.settleType==""){
        return layer.open({
          content: "奖励方式不能为空",
          skin: "msg",
          time:  2 //1秒后自动关闭
        });
      }else if(this.form.productNoList==[]){
        return layer.open({
          content: "活动商品不能为空",
          skin: "msg",
          time:  2 //1秒后自动关闭
        });
      }else if (this.form.openRewardAmt == "") {
        // this.dialogVisible=true
        return layer.open({
            content: "开通金额不能为空",
            skin: "msg",
            time:  2 //1秒后自动关闭
          });
       }else if (this.form.openRewardAmt <= 0) {
        // this.dialogVisible=true
        layer.open({
            content: "开通金额必须大于0",
            skin: "msg",
            time:  2 //1秒后自动关闭
          });
      }else if(this.form.coverPhotos.length<=0){
        layer.open({
            content: "至少上传一张banner图",
            skin: "msg",
            time:  2 //1秒后自动关闭
          });
      }else if(this.form.bgPhotos.length<=0){
           layer.open({
            content: "至少上传一张详情图",
            skin: "msg",
            time:  2 //1秒后自动关闭
          });
      }else {
            // https.saveOpenRewordActive(this.form)
            axios({
        url:'/api/active/saveOpenRewordActive',
        data:this.form,
        method:"post",
        timeout:1000*60*2
      }).then(res => {
              if (res.data.code == "0000") {
                this.loading=false
                this.$router.push("activityManagement");
              } else {
                this.loading=false
                layer.open({
                  content: res.data.msg,
                  skin: "msg",
                  time:  2 //1秒后自动关闭
                });
              }
            }).catch(err=>{})
      }
      console.log(this.form);

      // this.$router.push("activityManagement")
    },
    changeSel(val) {
      this.form.spType = val;
      this.pinpaiId = val; //品牌id
      console.log("发生改变");
      https.toChannelTypequeryProductList({channelType: val})
        .then(res => {
          console.log(res);
          //活动商品
          this.optionsBrandTypeNum = res.data.data;
        })
        .catch(err => {
          console.log(err);
        });
    },
    //请求品牌类型的接口
    pinChange(val) {
      console.log("id是");
      this.form.BrandTypeNum = [];
      console.log(val);
      //品牌id
      this.brandId = val;
      var ids = this.form.Brand;

      //根据品牌获取商品
      https.activeBrand({ brandChannelId: val })
        .then(res => {
          console.log("这里");
          console.log(res);
          // this.BrandTypeNum = res.data.data
          this.optionsBrandTypeNum = res.data.data;
        })
        .catch(err => {
          console.log(err);
        });
    },
    xingType(val) {
      const length = val.length;
      this.form.productNoList = [];
      console.log("下面是val");
      console.log(val);
      for (var i = 0; i < length; i++) {
        this.form.productNoList.push({
          channelUid: this.brandId,
          productUid: val[i]
        });
      }
    }
  }
};
</script>

<style scoped>
.con {
  position: relative;
}
/deep/ .el-tag__close {
  display: none !important;
}
.wrap {
  width: 96%;
  margin: 0 auto;
}
.listGroup {
  display: flex;
  flex-wrap: wrap;
  /* padding-left: 60px; */
  box-sizing: border-box;
  float: left;
}
.maiLister {
  font-size: 16px;
  color: #303133;
  font-weight: 600;
  margin-bottom: 30px;
  margin-top: 20px;
}
.lister {
  width: 450px;
  display: flex;
  justify-content: left;
  margin-bottom: 20px;
  align-items: center;
}
.listers {
  width: 100%;
  display: flex;
  justify-content: left;
  margin-bottom: 20px;
  align-items: center;
}
.listName {
  width: 90px;
  color: #909399;
  text-align: right;
  margin-right: 10px;
}
.listNames {
  width: 90px;
  color: #909399;
  text-align: right;
  margin-right: 10px;
}
.nums {
  display: inline-block;
  margin-right: 10px;
  color: #909399;
}
.mainTitle {
  font-size: 16px;
  font-weight: bold;
  color: #303133;
  margin: 20px 0;
  font-weight: 600;
}
/deep/ .el-input__inner {
  width: 300px;
}
/deep/ .el-input {
  width: 300px;
}
/deep/ .el-popper {
  width: 300px;
}
.add {
  position: absolute;
  left: 650px;
  top: -62px;
}
.delete {
  cursor: pointer;
  left: 10px;
  position: relative;
}
/deep/ .timers .el-range-separator {
  width: 20px;
}
.topTitle {
  /* font-weight: bold; */
  font-size: 16px;
  margin-top: 40px;
  color: #2f2c29;
  margin-bottom: 20px;
  /* margin-bottom: 40px; */
}
.foot {
  margin-top: 50px;
  padding-left: 40%;
}
/* 单独样式 */
.contbox6_10 {
  width: 100%;
  /* margin-left: 2%; */
  /*  height: 87.5vh; */
  overflow-x: auto;
  box-sizing: border-box;
  float: left;
}
.jibenInfo {
  width: calc(100% - 40px);
  margin:  0 20px;
  height: 40px;
  line-height: 40px;
  float: left;
  font-size: 18px;
}
.relus {
  width: 100%;
  height: 30px;
  line-height: 30px;
  padding-left: 20px;
  background: #f9f4f7;
}
</style>
<style>
.disabled .el-upload--picture-card {
  display: none;
}
</style>
